#!/usr/bin/env ruby

require 'Xml'


class Wsdl < Xml
  
  def operations
    if isDoc?
      return doc.xpath("//*[local-name()='operation']")
    end
    nil
  end
  
  def messages(operation = nil)
    if isDoc?
      operation = doc.xpath("//*[local-name()='operation' and @name = '#{operation}']")[0] if operation.class == "".class
      operation = operations[0] if operation.nil?
      return operation.elements
    end
    nil
  end
  
  def message_element_name(message = nil)
    if isDoc?
      return message_element(message).value.split(":")[-1]
    end
    nil
  end
  
  def message_element(message = nil)
    if isDoc?
      message = doc.xpath('//*[contains(@message,"#{message}")]')[0] if message.class == "".class
      message = messages[0] if message.nil?
      message = message.attributes["message"].value.split(":")[-1]
      message = doc.xpath("//*[local-name()='message' and @name = '#{message}']//@element|@type")[0]
      return message
    end
    nil
  end
  
  def element_schema(name)
    if isDoc?
      scm = doc.xpath("//*[contains('element,complexType',local-name()) and @name = '#{name.split(":")[-1]}']")[0]
      if scm.nil?
	ns = namespace(name.split(":")[0])
	path = element_schema_path(name)
	path = Xml.find_path(path) if !File.exist?(path)
	src = Xml.new(path) if !path.nil?
	scm = src.doc.xpath("//*[contains('element,complexType',local-name()) and @name = '#{name.split(":")[-1]}']")[0] if !src.nil?
	return element_schema_path(name).split("/")[-1] if scm.nil?
      end
      return scm.to_xml if !scm.nil?
    end
    nil
  end
  
  def element_schema_path(name)
    if isDoc?
      ns = namespace(name)
      imports.each do |i|
	path = i["schemaLocation"] if i["namespace"] == ns
	return path if !path.nil?
      end
    end
    "wsdl:types"
  end
  
  def type
    WSDL
  end

end

